<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios的拦截器</title>
  </head>

  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <style>
    body {
      margin: 0 auto;
    }

    .div {
      margin: 40px auto;
      width: 1000px;
    }
  </style>

  <body>
    <div class="div">
      <h2>axios的拦截器</h2>
      <hr>
      <button type="button" class="btn btn-primary">发送get请求</button>
      <button type="button" class="btn btn-danger">发送post请求</button>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    let btns = document.querySelectorAll(".btn");
    // 创建实例对象
    let instance = axios.create({
      //  默认方法
      method: "get",
      //  默认URL
      baseURL: "http://iwenwiki.com:3000/comment/music",
      // 默认超时时长
      timeout: 4000,
      // 默认参数
      params: {
        id: 186016,
        limit: 1
      }
    });



    // 添加一个请求拦截器
    instance.interceptors.request.use(function (config) {
      // Do something before request is sent
      console.log("请求拦截器成功");
      // console.log(config);
      config.data = 10001;
      // 修改配置
      return config;
    }, function (error) {
      // Do something with request error
      console.log("请求拦截器失败");
      return Promise.reject(error);
    });

    // 添加一个响应拦截器
    instance.interceptors.response.use(function (response) {
      // Any status code that lie within the range of 2xx cause this function to trigger
      // Do something with response data
      console.log("响应拦截器成功");
      return response.data;
    }, function (error) {
      // Any status codes that falls outside the range of 2xx cause this function to trigger
      // Do something with response error
      console.log("响应拦截器失败");
      return Promise.reject(error);
    });

    // 1.发送get请求
    btns[0].addEventListener('click', function () {
      instance({
          url: "/posts",
        }).then((resource) => {
          console.log(resource);
        })
        .catch((error) => {
          console.log(error);
        })
    });

    //2.发送post的请求:添加一个
    btns[1].onclick = function () {
      instance({
          method: "post",
          url: "/posts",
          data: {
            name: "tom",
            title: "Java从入门到放弃"
          }
        })
        .then((resource) => {
          console.log(resource);
        })
        .catch((error) => {
          console.log(error);
        })
    }
  </script>

</html>